package learn_concurrent._11;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class AtomicReferenceFieldUpdaterTest2 {

	public static void main(String[] args) throws InterruptedException {
		Person person = new Person();

		new Thread(() -> {
			person.setName("Tom");
			System.out.println(person);
		}).start();

		Thread.sleep(1000);

		person.setName("Jim");

		System.out.println(person);
	}

}

class Person {
	private volatile String name;

	private static final AtomicReferenceFieldUpdater<Person, String> nameUpdater = AtomicReferenceFieldUpdater
			.newUpdater(Person.class, String.class, "name");

	public String getName() {
		return name;
	}

	public void setName(String name) {
		while (true) {
			if (nameUpdater.compareAndSet(this, this.name, name)) {
				break;
			}
		}
	}

	@Override
	public String toString() {
		return "Person [name=" + name + "]";
	}

}
